<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 添加角色 -->
      <el-button type="primary" @click="dialogVisible = true">添加角色</el-button>
      <!-- 角色列表区 -->
      <el-table :data="roleslist" border stripe>
        <!-- 展开列 -->
        <el-table-column width="50" type="expand">
          <!-- 角色权限列表 -->
          <template v-slot="scope">
            <!-- {{scope.row}}该条角色的所有信息 -->

            <!-- 引用栅格系统布局分级权限 -->
            <!-- 利用循环列出所有分级权限 -->
            <!-- r1 下标索引 -->
            <el-row
              v-for="(item1,i1) in scope.row.children"
              :key="item1.id"
              border
              :class="['bdbottom',i1===0? 'bdtop':'','vcenter']"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二三级权限 -->
              <el-col :span="19">
                <!-- 通过循环item1渲染数二级权限 -->
                <el-row
                  v-for="(item2,i2) in item1.children"
                  :key="item2.id"
                  :class="[i2===0? '':'bdtop','vcenter']"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row,item2.id)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>

                  <!-- 通过循环item2渲染数三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRightById(scope.row,item3.id)"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- //索引项 -->
        <el-table-column width="50" type="index"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column width="300px" prop="mobile" label="操作">
          <template slot-scope="scope">
            <!-- slot-scope="scope"定义属性插入具名插槽 -->
            <!-- 修改信息 -->
            <!-- {{scope.row.id}} -->
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="showEdiDialog(scope.row.id)"
            >编辑</el-button>

            <!-- 更改角色 -->
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-star-off"
              @click="setRoles(scope.row)"
            >分配权限</el-button>

            <!-- 删除 -->
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="removeUserById(scope.row.id)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色弹框 -->
    <el-dialog title="添加角色" :visible.sync="dialogVisible" width="60%" @close="addDialogClosed">
      <!-- @close关闭输入框触发 -->
      <el-form :model="addForm" ref="addRolesRef" label-width="80px">
        <el-form-item label="角色名称" prop="rolesName">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 添加角色的底部 -->
      <span>
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑弹出框 -->
    <el-dialog title="编辑角色" :visible.sync="editDialogVisible" width="60%">
      <el-form :model="editForm" ref="editRolesRef" label-width="80px">
        <el-form-item label="角色名称" prop="rolesName">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 编辑角色的底部 -->
      <span>
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色权限弹出框 -->
    <el-dialog title="分配权限" :visible.sync="setDialogVisible" width="50%" @close="setRolesClosed">
      <!-- @close="setRolesClosed" 关闭弹出框之后清空原有权限id -->
      <!-- 树形控件 -->
      <el-tree
        :data="rightslist"
        :props="defaultProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defkeys"
        ref="treeRef"
      ></el-tree>
      <span>
        <el-button @click="setDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { log } from 'util'
import { get } from 'http'
export default {
  data() {
    return {
      //所有角色列表数据
      roleslist: [],
      //控制添加角色框的弹出
      dialogVisible: false,
      //控制编辑框的弹出
      editDialogVisible: false,
      //添加的角色信息
      addForm: {
        roleName: '',
        roleDesc: ''
      },
      //编辑中由id获取到的用户的信息
      editForm: {},
      //控制分配权限弹出框的弹出
      setDialogVisible: false,
      //所有的权限列表数据
      rightslist: [],
      //树形控件嵌套规则
      defaultProps: {
        children: 'children',
        label: 'authName'
      },
      // 树形控件选中权限的id数据
      defkeys: [],
      //分配权限当前角色id
      roleId: ''
    }
  },
  created() {
    this.getRoleslist()
  },
  methods: {
    async getRoleslist() {
      const { data: res } = await this.$http.get('/roles')
      console.log(res)

      if (res.meta.status !== 200)
        return this.$message.error('获取角色列表失败')
      this.$message.success('获取角色列表成功')
      this.roleslist = res.data
    },
    //添加框关闭之后触发该属性,清空添加框的值
    addDialogClosed() {
      this.$refs.addRolesRef.resetFields()
    },

    //添加角色按钮
    async addUser() {
      //发送请求获取角色信息
      const { data: res } = await this.$http.post('/roles', this.addForm)
      console.log(res)
      if (res.meta.status !== 201) return this.$message.error('添加失败')
      this.$message.success('添加成功')
      //关闭该窗口
      this.dialogVisible = false
      //重新加载数据
      this.getRoleslist()
    },
    //操作编辑按钮由id获取用户信息
    async showEdiDialog(id) {
      console.log(id)
      this.editDialogVisible = true
      const { data: res } = await this.$http.get('roles/' + id)
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('角色信息失败')
      this.editForm = res.data
    },
    //点击编辑确认按钮
    async editUser() {
      const { data: res } = await this.$http.put(
        'roles/' + this.editForm.roleId,
        {
          roleName: this.editForm.roleName,
          roleDesc: this.editForm.roleDesc
        }
      )
      console.log(res)
      if (res.meta.status !== 200)
        return this.$message.error('修改角色信息失败')
      this.$message.success('修改角色信息成功')
      //关闭该窗口
      this.editDialogVisible = false
      //重新加载数据
      this.getRoleslist()
    },
    //删除按钮
    async removeUserById(id) {
      // 弹框提示是否删除
      const confiemResult = await this.$confirm(
        '此操作将永久删除该角色, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(res => res)
      //表示按下取消按钮输出
      //cancel 取消
      // 删除确认输出
      console.log(confiemResult) //confirm删除
      // 取消删除
      if (confiemResult !== 'confirm') return this.$message.info('取消了删除')
      // 确认删除
      const { data: res } = await this.$http.delete('roles/' + id)
      console.log(res)
      if (res.meta.status !== 200) this.$message.error('删除角色失败')
      this.$message.success('删除角色成功')
      //重新加载数据
      this.getRoleslist()
    },
    //删除权限
    async removeRightById(role, id) {
      console.log(role)

      // 弹框提示是否删除
      const confiemResult = await this.$confirm(
        '此操作将永久删除该角色, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      console.log(confiemResult)
      if (confiemResult !== 'confirm') return this.$message.info('取消了删除')
      console.log('确认删除')
      //发送请求删除角色指定权限
      console.log(role.id)
      console.log(id)
      const { data: res } = await this.$http.delete(
        'roles/' + role.id + '/rights/' + id
      )
      console.log(res)

      if (res.meta.status !== 200)
        return this.$message.error('删除角色权限失败')
      this.$message.success('删除角色权限成功')
      // 删除成功后重新加载数据
      // this.getRoleslist()
      // 上步操作会关闭当前下拉框,所以给当前角色从新赋值权限
      role.children = res.data
    },
    // 分配权限按钮
    async setRoles(role) {
      // 保存当前所选角色的id
      this.roleId = role.id
      // 获取所有权限列表
      const { data: res } = await this.$http.get('rights/tree')
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('获取权限失败')
      console.log('获取权限成功')
      // 获取到的权限数据保存到data中
      this.rightslist = res.data
      console.log(this.rightslist)

      //在权限列表弹出之前,应该先调用递归函数获取三级列表id,先接收传递过来选中条的数据
      this.getLeafKeys(role, this.defkeys)

      // 弹出权限框
      this.setDialogVisible = true
    },
    //利用递归获取到所有三级权限的id
    getLeafKeys(node, arr) {
      //如果当前node节点不包含children,则表示为三级权限,添加到arr中
      if (!node.children) {
        return arr.push(node.id)
      }
      //如果有children,这边表示不为三级,继续递归该函数直到没有children为止
      node.children.forEach(item => this.getLeafKeys(item, arr))
    },
    //监听权限弹出框的关闭,之后清空原有权限id
    setRolesClosed() {
      this.defkeys = []
    },
    // 确认分配权限按钮
    async allotRights() {
      // const allotRightsKey = [
      //   ...this.$refs.treeRef.getHalfCheckedKeys(),
      //   ...this.$refs.treeRef.getCheckedKeys()
      // ]
      // console.log(allotRightsKey)
      // const idStr = allotRightsKey.join(',')
      //获取半选状态
      this.$refs.treeRef.getHalfCheckedKeys()
      console.log(this.$refs.treeRef.getHalfCheckedKeys(), 333)

      // 获取全选状态权限
      this.$refs.treeRef.getCheckedKeys()
      console.log(this.$refs.treeRef.getHalfCheckedKeys(), 222)
      // 获取所有选取状态权限id
      const allotRightsKey = [
        this.$refs.treeRef.getHalfCheckedKeys(),
        this.$refs.treeRef.getCheckedKeys()
      ]
      const idStr = allotRightsKey.join(',')
      console.log(idStr, 111)
      //发送请求,更新角色权限
      const { data: res } = await this.$http.post(
        'roles/' + this.roleId + '/rights',
        { rids: idStr }
      )
      console.log(res)
      if (res.meta.status !== 200) return rhis.$message.error('更新权限失败')
      this.$message.success('更新权限成功')
      //重新加载数据
      this.getRoleslist()
      //关闭分配框
      this.setDialogVisible = false
    }
  }
}
</script>
<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
// 顶边框
.bdtop {
  border-top: 1px solid #eee;
}
// 边底框
.bdbottom {
  border-bottom: 1px solid #eee;
}
//居中对齐 类
.vcenter {
  display: flex;
  align-items: center;
}
</style>
